package com.demo.juc.lock;

import ch.qos.logback.core.util.TimeUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: jxm
 * @Description:
 * 读-读能共存
 * 读-写不能共存
 * 写-写不能共存
 * 写操作：原子+独占，整个过程必须是一个完整的统一体，中间不许被分割，被打断
 * @Date: 2022/4/2 10:11
 * @Version: 1.0
 */
public class ReentrantReadWriteLockTest {


    public static void main(String[] args){

        MyCache cache = new MyCache();

        for (int i = 1; i < 6; i++) {
            final int tempInt = i;
            new Thread(()->{
                cache.put(tempInt + "",tempInt + "");
            },String.valueOf(i)).start();
        }

        for (int i = 1; i < 6; i++) {
            final int tempInt = i;
            new Thread(()->{
                cache.get(tempInt + "");
            },String.valueOf(i)).start();
        }

    }

}

/**
 * 资源类 ReentrantReadWriteLock
 */
class MyCache{

    private volatile Map<String,Object> map = new HashMap();
    private ReadWriteLock readWriteLock = new java.util.concurrent.locks.ReentrantReadWriteLock();

    public void put(String key,Object value){

        try {
             readWriteLock.writeLock().lock();
            System.out.println(Thread.currentThread().getName()+"\t 正在写入" + key);
            try {
                TimeUnit.MICROSECONDS.sleep(300);
                map.put(key,value);
                System.out.println(Thread.currentThread().getName()+"\t 写入完成" + key);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            readWriteLock.writeLock().unlock();
        }


    }

    public void get(String key){
        try {
            readWriteLock.readLock().lock();
            System.out.println(Thread.currentThread().getName()+"\t 正在读取");
            try {
                TimeUnit.MICROSECONDS.sleep(300);
                Object value = map.get(key);
                System.out.println(Thread.currentThread().getName()+"\t 读取完成" + value);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            readWriteLock.readLock().unlock();
        }

    }
}
